package com.gonsin.gview.logic.services;

import com.gonsin.gview.logic.config.GViewFileProperties;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class GFileServiceImpl {

    @Autowired(required = false) private GViewFileProperties config;

    public String getPathFromUrl(String url) {
        String tempPath = config == null ? "C:/temp" : config.getTempPath();
        if(url == null){
            return null;
        }
        String filename = url.substring(6);
        return tempPath + File.separator + filename;
    }

    /**
     * 在临时文件夹新建一个文件
     */
    public File newTempFile(String ext) {
        String tempPath = config == null ? "C:/temp" : config.getTempPath();
        String path = tempPath + File.separator + RandomStringUtils.random(32, true, true) + "." + ext;
        File file = new File(path);
        if(!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /**
     * 转换路径为url
     */
    public String getUrlFromPath(String path) {
        String fileName = FilenameUtils.getName(path);
        return "/temp/" + fileName;
    }

}
